/**
 * 
 */
package org.dragonfire.dasm.linkers;

import java.util.ArrayList;
import java.util.List;

import org.dragonfire.dasm.DASM;

/**
 * @author Darth Android
 * @date Aug 24, 2007
 */
public class LinkerIhex extends Linker {

	public static final int BLOCK_SIZE = 24;
	public static final char START_CHAR = ':';

	@Override
	public List<Byte> link(DASM comp, List<Byte> data) {
		int blockSize = BLOCK_SIZE;
		char startChar = START_CHAR;
		// TODO read in config info if exists
		if (comp.getParam("ihex-block-size") != null) {
			blockSize = comp.evalInt(comp.getParam("ihex-block-size"));
		}
		byte[] input = new byte[data.size()];
		for (int i = 0; i < data.size(); i++) {
			input[i] = data.get(i);
		}
		String output = writeHex(input, blockSize, startChar, 0);
		// convert output to List<Byte> and return it
		byte[] temp = output.getBytes();
		data = new ArrayList<Byte>();
		for (byte tempByte : temp) {
			data.add(tempByte);
		}
		return data;
	}

	public static String writeHex(byte[] data, int blockSize, char startChar, int startAddr) {
		String output = "";
		int idx = 0;
		byte checkSum = 0;
		while (idx < data.length) {
			checkSum = (byte) (((startAddr >> 8) & 0xFF) + (startAddr & 0xFF));
			output += startChar + String.format("%02X%04X00", blockSize, startAddr);
			int i;
			for (i = 0; i < blockSize && idx < data.length; i++) {
				checkSum += data[idx];
				output += String.format("%02X", data[idx++]);
			}
			output += String.format("%02X", (byte) ((~(checkSum + i)) + 1)) + "\r\n";
			startAddr += blockSize;
		}
		return output + ":00000001FF";
	}
}
